//
//  EDBangdingPhoneOrEmailViewCobntroller.m
//  EDF
//
//  Created by 微笑吧阳光 on 2019/7/12.
//  Copyright © 2019 p. All rights reserved.
//

#import "EDBangdingPhoneOrEmailViewCobntroller.h"
#import "BangDingPhoneInfoView.h"
#import "UIButton+CountDown.h"
#import "EDChangeWithdrawalsCodeViewController.h"
#import "LLWebViewController.h"
#import "UIBarButtonItem+CABarButton.h"
@interface EDBangdingPhoneOrEmailViewCobntroller ()
@property (nonatomic,strong) UIBarButtonItem *rightBarButton;
@property(nonatomic,strong)BangDingPhoneInfoView * infoView;
@property(nonatomic,strong) NSData  * imageDataStr;
@property(nonatomic,copy)    NSString  * imageKey;

@end

@implementation EDBangdingPhoneOrEmailViewCobntroller

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    self.infoView.frame =CGRectMake(0, kStatusBarAndNavigationBarHeight, kScreenWidth, 500);
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self creatUI];
    if (self.showType!=2) {
        [self requestKeFu];
    }else{
           self.navigationItem.rightBarButtonItem = self.rightBarButton;
    }

    [self requestImageCodeData];
    
}


//联系客户
- (void)chatbutton
{
    LLWebViewController * webview = [[LLWebViewController alloc] init];
    webview.urlStr = @"https://sv36.saasview.com/chat/Hotline/channel.jsp?cid=5008919&cnfid=3938&j=5614631401&s=1";
    webview.isType = 1;
    webview.titleStr = @"联系客服";
    [[WJUnit currentViewController].navigationController pushViewController:webview animated:YES];
}
- (UIBarButtonItem*)rightBarButton {
    if (!_rightBarButton) {
        _rightBarButton = [UIBarButtonItem  RightitemWithImageNamed:@"" title:@"客服" target:self action:@selector(chatbutton)] ;
    }
    return _rightBarButton;
}
-(void)creatUI
{
    self.infoView= [[NSBundle mainBundle]loadNibNamed:@"BangDingPhoneInfoView" owner:self options:nil].lastObject;
    self.infoView.frame =CGRectMake(0, kStatusBarAndNavigationBarHeight, kScreenWidth, 500);
    [self.view addSubview:self.infoView];
    if (self.showType==1 || self.showType==2) {
        [self.infoView.sureBtn setTitle:@"下一步" forState:0];
        
    }
    if (self.showType==2) {
        self.infoView.lab2.hidden = NO;
    }else{
         self.infoView.lab2.hidden = YES;
    }
    
    WEAKSELF
    [self.infoView.codeRefushBtn add_BtnClickHandler:^(NSInteger tag) {
        STRONGSELFFor(weakSelf);
        [strongSelf requestImageCodeData];
    }];
    [self.infoView.sureBtn add_BtnClickHandler:^(NSInteger tag) {
         STRONGSELFFor(weakSelf);
        [strongSelf sureBtnClick:strongSelf.infoView.sureBtn];
    }];
    
    [self.infoView.codeActionBtn add_BtnClickHandler:^(NSInteger tag) {
        STRONGSELFFor(weakSelf);
        [strongSelf phoneCodeBtnClick:strongSelf.infoView.codeActionBtn];
    }];
    
}

-(void)requestKeFu{
    
    WEAKSELF
    NSString  * url2 = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"Game_getUserExclusiveCustomer"];
    [[SmileHttpTool sharedInstance] GET :url2 parameters:nil origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        [self stopLoadingAnimation];
        STRONGSELFFor(weakSelf)
        NSError *errorData;
        NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
        NSDictionary *dict001 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
        NSString *responseObjectStr =[dict001 jsonString:@"statusCode"];
        if ([responseObjectStr isEqualToString:@"SUCCESS"]) {
            YYLog(@"Game_getUserExclusiveCustomer----%@",dict001);
            
            NSDictionary * dicc = [dict001 jsonDict:@"data"];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.infoView.lab2.text = [NSString stringWithFormat:@"如收不到验证码，请联系%@ %@",[dicc jsonString:@"txt"],[dicc jsonString:@"remark"]];
                NSString *termsString = [NSString stringWithFormat:@"如收不到验证码，请联系%@ %@",[dicc jsonString:@"txt"],[dicc jsonString:@"remark"]];
                NSMutableAttributedString * attString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"如收不到验证码，请联系%@ %@",[dicc jsonString:@"txt"],[dicc jsonString:@"remark"]]];
                [attString addAttributes:@{NSForegroundColorAttributeName:EDColor_BaseBlue} range:[termsString rangeOfString:[dicc jsonString:@"remark"]]];//改变范围颜色
                [self.infoView.lab2 setAttributedText:attString];
                 self.infoView.lab2.hidden = NO;
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1 andImageName:@"error" andTitleStr:[dict001 jsonString:@"message"] andlightStr:@""];
                [toast showLXAlertView];
            });
        }
    } failure:^(id responseObject, NSError *error) {
        NSLog(@"error----%@",error);
        [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
    }];
}
-(void)sureBtnClick:(UIButton *)sender{
    
    if (self.showType==1) {
        NSString  * phoneStr = [[DJLoginHelper sharedInstance].cj_UserDicc jsonString:@"phone"];
        if (![phoneStr isEqualToString:self.infoView.numTF.text]) {
            
            [JMNotifyView showNotify:[NSString stringWithFormat:@"请输入已绑定尾号为%@的手机号",[phoneStr substringFromIndex:phoneStr.length-4] ] isSuccessful:NO];
            
            return;
        }
        
    }
    
    [self cheak_mobNum];
    
}
-(void)cheak_mobNum{
    if (kStringIsEmpty(self.infoView.numTF.text)) {
       [JMNotifyView showNotify:@"请输入手机号" isSuccessful:NO];
       return;
    }
   if ([NSString  isMobileNumChack:self.infoView.numTF.text]==NO) {
       [JMNotifyView showNotify:@"请输入正确格式的手机号~" isSuccessful:NO];
        return;
    }
    [self cheack_RomCode];
}
-(void)cheack_RomCode{
 
    if (kStringIsEmpty(self.infoView.codeImageTF.text)) {
        [JMNotifyView showNotify:@"请输入随机图形码" isSuccessful:NO];
        return;
    }
    
    [self cheack_PhoneCode];
    
}
-(void)cheack_PhoneCode{

    if (kStringIsEmpty(self.infoView.codeNumTF.text)) {
        [JMNotifyView showNotify:@"请输入手机验证码" isSuccessful:NO];
        return;
    }
    
    [self chack_ImageCodeRequest];
    
}
-(void)requestImageCodeData{
    // LogincOnLoadOCode
    NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"LogincOnLoadOCode"];
    WEAKSELF
    [[SmileHttpTool sharedInstance] GET_Data :url parameters:nil origin:YES success:^(NSInteger statusCode,NSURLSessionDataTask *  task,id responseObject) {
        STRONGSELFFor(weakSelf)
        YYLog(@"responseObject----%@",responseObject);
       strongSelf.imageDataStr = [NSData dataWithData:responseObject];
        NSHTTPURLResponse *httpURLResponse = (NSHTTPURLResponse*)task.response;
        NSDictionary *allHeaderFieldsDict = httpURLResponse.allHeaderFields;
        NSLog(@"allHeaderFieldsDict---%@",allHeaderFieldsDict);
        strongSelf.imageKey = [allHeaderFieldsDict jsonString:@"cpkey"];
        strongSelf.infoView.codeImage.image =  [UIImage imageWithData:strongSelf.imageDataStr];
    } failure:^(id responseObject, NSError *error) {
        NSLog(@"error----%@",error);
         [WJUnit showMessage:@"请求错误"];
    }];
    
}
-(void)chack_ImageCodeRequest{
    NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"Code_verificationRandomCode"];
    NSMutableDictionary  *dicc = [NSMutableDictionary dictionary];
    [dicc setValue:self.infoView.codeImageTF.text forKey:@"code"];
    WEAKSELF
    [[SmileHttpTool sharedInstance] GET_DataDChackImageCode:url imageKey:self.imageKey parameters:dicc origin:YES success:^(NSInteger statusCode, NSURLSessionDataTask *task, id responseObject) {
        STRONGSELFFor(weakSelf);
       // NSLog(@"LoginccCheckImageCodeAction----%@",responseObject);
        NSString* strdata = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSData * data =[[strdata URLDecodedString] dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
        NSDictionary *dict001 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        NSString *responseObjectStr =[dict001 jsonString:@"statusCode"];
        if ([responseObjectStr isEqualToString:@"SUCCESS"]) {
            if (strongSelf.showType==2) {
//                if (strongSelf.dismissWithPhoneCode) {
//                    strongSelf.dismissWithPhoneCode(strongSelf.infoView.codeNumTF.text, strongSelf.infoView.numTF.text);
//                }
//               // [strongSelf.navigationController popViewControllerAnimated:YES];
                EDChangeWithdrawalsCodeViewController *awalsCodeVC = [EDChangeWithdrawalsCodeViewController new];
                awalsCodeVC.showType =10086;
                awalsCodeVC.title = @"修改登录密码";
                awalsCodeVC.phone = strongSelf.infoView.numTF.text;
                awalsCodeVC.codeStr = strongSelf.infoView.codeNumTF.text;
                [self.navigationController pushViewController:awalsCodeVC animated:YES];
                
            }else{
                   [strongSelf cheak_PhoneCode];
            }
         
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1 andImageName:@"error" andTitleStr:[dict001 jsonString:@"message"] andlightStr:@""];
                [toast showLXAlertView];
            });
        }
        
    } failure:^(id responseObject, NSError *error) {
        [JMNotifyView showNotify:@"校验图形验证码，网络错误，请重试~" isSuccessful:NO];
        [self stopLoadingAnimation];
    }];
    
}

-(void)cheak_PhoneCode{
   // Code_verificationPhoneCode
    NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"Code_verificationPhoneCode"];
    NSMutableDictionary  *dicc = [NSMutableDictionary dictionary];
    [dicc setValue:self.infoView.codeNumTF.text forKey:@"code"];
    [dicc setValue:self.infoView.numTF.text forKey:@"tel"];
    WEAKSELF
    [[SmileHttpTool sharedInstance] GET :url parameters:dicc origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
        STRONGSELFFor(weakSelf)
        NSError *errorData;
        NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
        NSDictionary *dict001 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
        NSString *responseObjectStr =[dict001 jsonString:@"statusCode"];
        if ([responseObjectStr isEqualToString:@"SUCCESS"]) {
            if (self.showType==0) {
                  [strongSelf UserCode_bandUserPhone];
            }else{
                if (strongSelf.dismissWithPhoneCode) {
                strongSelf.dismissWithPhoneCode(strongSelf.infoView.codeNumTF.text, strongSelf.infoView.numTF.text);
                }
                [strongSelf.navigationController popViewControllerAnimated:YES];
            }
          
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1 andImageName:@"error" andTitleStr:[dict001 jsonString:@"message"] andlightStr:@""];
                [toast showLXAlertView];
            });
        }
    } failure:^(id responseObject, NSError *error) {
        [self stopLoadingAnimation];
        NSLog(@"error----%@",error);
        [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
    }];
 
}
-(void)phoneCodeBtnClick:(UIButton *)sender{
    
    if (self.showType==1) {
          NSString  * phoneStr = [[DJLoginHelper sharedInstance].cj_UserDicc jsonString:@"phone"];
        if (![phoneStr isEqualToString:self.infoView.numTF.text]) {
            
              [JMNotifyView showNotify:[NSString stringWithFormat:@"请输入已绑定尾号为%@的手机号",[phoneStr substringFromIndex:phoneStr.length-4] ] isSuccessful:NO];
            
            return;
        }

    }
  
    
    if (kStringIsEmpty(self.infoView.numTF.text)) {
        [JMNotifyView showNotify:@"请输入手机号" isSuccessful:NO];
        return;
    }
    if ([NSString  isMobileNumChack:self.infoView.numTF.text]==NO) {
        [JMNotifyView showNotify:@"请输入正确格式的手机号~" isSuccessful:NO];
        return;
    }
    
    if (kStringIsEmpty(self.infoView.codeImageTF.text)) {
        [JMNotifyView showNotify:@"请输入随机图形码" isSuccessful:NO];
        return;
    }

    if (self.showType==2) {
        //UserCode_SendMsgMobileAction22
        NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"UserCode_SendMsgMobileAction"];
        NSMutableDictionary  *dicc = [NSMutableDictionary dictionary];
        [dicc setValue:self.infoView.numTF.text forKey:@"tel"];
        [dicc setValue:self.infoView.codeImageTF.text forKey:@"code"];
        [dicc setValue:self.imageKey forKey:@"cpkey"];
        WEAKSELF
        [[SmileHttpTool sharedInstance] GET :url parameters:dicc origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
            STRONGSELFFor(weakSelf)
            NSError *errorData;
            NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
            NSDictionary *dict001 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
            NSString *responseObjectStr =[dict001 jsonString:@"statusCode"];
            if ([responseObjectStr isEqualToString:@"SUCCESS"]) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [sender scheduledTimerWithTimeInterval:60.0f title:@"重新获取" countDownTitle:@"s" titleBackgroundColor:EDColor_BaseBlue countDownTitleBackgroundColor:EDColor_BaseBlue];
                    ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1.5 andImageName:@"success" andTitleStr:[NSString stringWithFormat:@"手机验证码已发送,注意查收"] andlightStr:@""];
                    [toast showLXAlertView];
                    
                });
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1 andImageName:@"error" andTitleStr:[dict001 jsonString:@"message"] andlightStr:@""];
                    [toast showLXAlertView];
                });
            }
            
        } failure:^(id responseObject, NSError *error) {
            NSLog(@"error----%@",error);
            [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
        }];
        
    }else{
        
        NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"UserCode_SendMsgMobileAction"];
        NSMutableDictionary  *dicc = [NSMutableDictionary dictionary];
        [dicc setValue:self.infoView.numTF.text forKey:@"tel"];
        [dicc setValue:self.infoView.codeImageTF.text forKey:@"code"];
        [dicc setValue:self.imageKey forKey:@"cpkey"];
        WEAKSELF
        [[SmileHttpTool sharedInstance] GET :url parameters:dicc origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
            STRONGSELFFor(weakSelf)
            NSError *errorData;
            NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
            NSDictionary *dict001 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
            NSString *responseObjectStr =[dict001 jsonString:@"statusCode"];
            if ([responseObjectStr isEqualToString:@"SUCCESS"]) {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [sender scheduledTimerWithTimeInterval:60.0f title:@"重新获取" countDownTitle:@"s" titleBackgroundColor:EDColor_BaseBlue countDownTitleBackgroundColor:EDColor_BaseBlue];
                    ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1.5 andImageName:@"success" andTitleStr:[NSString stringWithFormat:@"手机验证码已发送,注意查收"] andlightStr:@""];
                    [toast showLXAlertView];
                    
                });
            }else{
                dispatch_async(dispatch_get_main_queue(), ^{
                    ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1 andImageName:@"error" andTitleStr:[dict001 jsonString:@"message"] andlightStr:@""];
                    [toast showLXAlertView];
                });
            }
            
        } failure:^(id responseObject, NSError *error) {
            NSLog(@"error----%@",error);
            [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
        }];
        
    }

}

-(void)UserCode_bandUserPhone{
    [self showLoadingAnimation];
    NSString  * url = [[YINetWorkAPIGenerate sharedInstance] APINomark:@"UserCode_bandUserPhone"];
    NSMutableDictionary  *dicc = [NSMutableDictionary dictionary];
    [dicc setValue:self.infoView.codeNumTF.text forKey:@"code"];
    [dicc setValue:self.infoView.numTF.text forKey:@"tel"];
    WEAKSELF
    [[SmileHttpTool sharedInstance] GET :url parameters:dicc origin:YES success:^(NSInteger statusCode, NSString *message, id responseObject) {
           [self stopLoadingAnimation];
        STRONGSELFFor(weakSelf)
        NSError *errorData;
        NSData * data =[responseObject dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
        NSDictionary *dict001 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorData];
        NSString *responseObjectStr =[dict001 jsonString:@"statusCode"];
        if ([responseObjectStr isEqualToString:@"SUCCESS"]) {
    
                        dispatch_async(dispatch_get_main_queue(), ^{
            
                            ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1.5 andImageName:@"success" andTitleStr:[NSString stringWithFormat:@"绑定手机成功"] andlightStr:@""];
                            [toast showLXAlertView];
            
                            __block EDBangdingPhoneOrEmailViewCobntroller *weakSelf = self;
                            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
                            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                                if (weakSelf.dismiss) {
                                    weakSelf.dismiss(YES);
                                }
                                [weakSelf.navigationController popViewControllerAnimated:YES];
                            });
            
                        });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                ToastView * toast = [[ToastView alloc] initWithtToastandStayTime:1 andImageName:@"error" andTitleStr:[dict001 jsonString:@"message"] andlightStr:@""];
                [toast showLXAlertView];
            });
        }
    } failure:^(id responseObject, NSError *error) {
        [self stopLoadingAnimation];
        NSLog(@"error----%@",error);
        [JMNotifyView showNotify:@"网络错误，请重试~" isSuccessful:NO];
    }];
    
}

@end
